package com.atguigu.tingshu.account.receiver;

import com.atguigu.tingshu.account.service.UserAccountService;
import com.atguigu.tingshu.common.rabbit.constant.MqConst;
import com.rabbitmq.client.Channel;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
@Slf4j
public class AccountReceiver {
    @Autowired
    private UserAccountService userAccountService;
    /**
     * @author gengjian
     * @date 2025/02/25 15:51:33
     * 注册成功初始化用户账户信息
     */
    //bindings：1.在服务器内部实现队列与交换机的绑定关系
    //queues：1.当队列与交换机有绑定关系时，直接用queues
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConst.QUEUE_USER_REGISTER,durable = "true",autoDelete = "false"),
            exchange = @Exchange(value = MqConst.EXCHANGE_USER),
            key = MqConst.ROUTING_USER_REGISTER
    ))
    public void register(Long userId,Message message, Channel channel){
        System.out.println("用户注册成功！"+userId);
        //消息在哪里 取消息主体
        byte[] body = message.getBody();
        System.out.println(new String(body));
        //判断
        try {
            if (userId != null){
                userAccountService.register(userId);
            }
        } catch (Exception e) {
            //消费异常
            log.info("");
        }
        //手动确认消息，保证消息从队列中出队，否则会造成消息积压 表示是否批量签收
        try {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
